<?php
namespace app\api\controller;
use think\Controller;
use app\api\model\Cuser as Users;
use think\Loader;
use think\Request;
use text\TextCode;
use function think\select;
/**
 * 
 * @author sj
 * @description 普通会员登录控制器
 */
class User extends Controller{
    //登录默认为密码登录
    private static $cModel;
    
    public function __construct()
    {
        if(!self::$cModel instanceof self)
        {
            self::$cModel=new Users();
        }
    }
    public function Clogin()
    {
    $post_data=empty(input('post.'))?ajaxReturn2(-1,'data is null'):input('post.');
    $layout=$post_data['layout'];  
   
    
    $Cvalidate=Loader::validate('User');
    if(!$Cvalidate->check($post_data))
    {
    ajaxReturn2(-1,urlencode($Cvalidate->getError()),'');
    }
    //验证器校验
    //正则验证手机号是否正确 11位 并且是有效的手机号
    //只有这些成功后才去数据库进行查询 如果账号不存在退出
    $check=checkPhone2($post_data['telphone']);
    if(!$check)
    {
        ajaxReturn2(-1,'手机号格式不正确',$post_data['telphone']);
    }
  
    
   $res=self::$cModel->Clogin($post_data);
   if($res=='1'){
       ajaxReturn2(1,'登陆成功',url($post_data['c']."/".$post_data['a']));//返回给前端的状态吗 1代表账户登录成功
   }elseif($res=='0') {
       ajaxReturn2(0,'手机号或密码错误',$post_data);//代表账户存在密码错误
   }else{
       ajaxReturn2(2,'账号不存在请注册',url('User/regis'));//账户不存在注册
   }
    }
    //短信验证码登录
    public function Textlogin(){
        if(Request::instance()->isPost()){
            $post_data=empty(input('post.'))?ajaxReturn2(-1,'data is empty',''):input('post.');
            $telphone=input('post.telphone');
            $code=input('post.code');
            $Cvalidate=Loader::validate('Cvalidate');
            if(!$Cvalidate->check($post_data)){
                ajaxReturn2(-1,urlencode($Cvalidate->getError()));
            }
            $re=checkPhone2($telphone);
            if (!$re){
                ajaxReturn2(-1,'手机号格式不正确',$post_data);
            }
            //这里多一步用户账号没有自动注册
            $sin=self::$cModel->selectAccount($telphone);
            if(!$sin){
                $data=array('telphone'=>$telphone,'password'=>md5($telphone));
                self::$cModel->Cregister($data);
            }
           $re=$this->checkTextValidateCode($telphone,$code);
           if(!$re){
               ajaxReturn2(400,'验证码错误',$post_data);
           }else{
               //这里可以登录成功后返回一些权限
               ajaxReturn2(200,'ok',url('Userinfo/selectuserinfo'));
           }
            
        }
    }
    //注册手机号+密码+手机短信验证码
    public function Cregister(){
        if(Request::instance()->isPost())
        {
           $post_data=empty(input('post.'))?ajaxReturn2(2,'data is empty'):input('post.');
           $password=$post_data['password'];
           
           $telphone=$post_data['telphone'];
           
           $post_data['password']=md5($post_data['password']);
           //$data_new=array('telphone'=>$telphone,'password'=>$post_data['password']);
           //$CuserValidate=Loader::validate('User');
           /**if(!$CuserValidate->check($data_new))
           {
           ajaxReturn2(-1,$CuserValidate->getError());    
           }**/
           empty($telphone)?ajaxReturn2(-1,'手机号码不能为空'):"";
          
           $re=checkPhone2($telphone);
           if(!$re){
               ajaxReturn2(-2,'手机格式不正确',$post_data);
           }
           
           empty($password)?ajaxReturn2(-1,'密码不能为空'):"";
           $code=$post_data['code'];
           if(empty($code))
           {
               ajaxReturn2(-1,'请填写验证码',$post_data);
           }
           
            $result=$this->checkTextValidateCode($telphone,$code);
            if(!$result){
                ajaxReturn2(401,'验证码填写错误',$post_data);
            }
           
           //查询缓存中用户手机号的验证码有没有如果没有再次调用第三方接口
           //这里验证短信的验证码就是用户Post过来的数据 进行手机号密码 手机号格式 密码长度 验证码
           //这里还需要进行每次查询的js中发出post,get进行相关的算法时间搓进行加密传输数据 服务器进行解码看是否是
           //约定的正常的请求而不是非法请求
           
          //下面进行注册数据库添加的逻辑
          //添加注册看是否用户已存在
          
          $id=self::$cModel->Cregister($post_data);
          if($id){
              ajaxReturn2(200,'注册成功',url('User/login'));
          }else{
              ajaxReturn2(400,'register failed',$post_data);
          }
           
        }
    }
    //调用短信接口获取短信验证码
    public function getTextValidateCode(){
        //调用第三方短信验证码接口
        //返回的是这个手机号key value形式 存放session中有效时间
        //这里就是点击发送短信验证码
        //这个接口进行频率控制 调用次数进行控制
        
        $telphone=empty(input('get.telphone'))?ajaxReturn2(-1,'请填写手机号',''):input('get.telphone');
        $res=checkPhone2($telphone);
        if(!$res){
            ajaxReturn2(414,'手机号码格式不正确',$res);
        }
        
        $codeLength=4;
        //手机号账号如果已存在就需要再调用短信接口
        /**$te=$this->checkUserExsits($telphone);
        if($te)
        {
            ajaxReturn2(303,'user exsits',$telphone);//调用短信口用户存在让其登录弹出框
        }**/
        $TextCode=new TextCode(config('AppKey'), config('AppSecret'));
        
        $res=$TextCode->sendSmsCode(config('templateid'),$telphone,$codeLength);
        if($res['code']=='200'){
           ajaxReturn2(200,'短信发送成功',null);
           //前端进行提示发送成功
        }else{
           ajaxReturn2(400,'短信发送失败',$res);
           //提示发送失败,请五分钟后重试
        }
    }
    //校验短信验证码
    public function checkTextValidateCode($telphone="",$code=""){
        //这里是提交表单进行验证也可以异步
        $TextCode=new TextCode(config('Appkey'), config('AppSecret'));
        //$telphone='18795805742';
        //$code='7985';
        $res=$TextCode->checkTextCode($telphone, $code);
        if($res['code']=='200'){
            return 1;
        }else{
            return 0;
        }
    }
    
    public function checkTextValidateCodes(){
        //这里是提交表单进行验证也可以异步
        $telphone=input('post.telphone');
        $code=input('post.code');
        $res=checkPhone2($telphone);
        if(!$res){
            ajaxReturn2(-1,'手机号码格式不正确','');
        }
        if(empty($code)){
            ajaxReturn2(-1,'验证码不能为空',"");
        }
        
        $TextCode=new TextCode(config('Appkey'), config('AppSecret'));
        //$telphone='18795805742';
        //$code='7985';
        $res=$TextCode->checkTextCode($telphone, $code);
        if($res['code']=='200'){
           ajaxReturn2(200,'验证码填写正确',url('User/newPwd'));
        }else{
            ajaxReturn2(400,'验证码填写错误',$res);
        }
    }
    //测试
    public function test(){
       /**$tel='18012348902';
       $res=checkPhone2($tel);
       if($res){
           dump($res);
       }else{
           ajaxReturn2(-1,'telphone is error',$tel);
       }
       **/
        $this->getTextValidateCode('18795805742');
    }
    //检测用户是否存在
    
    public function checkUserAccount(){
        $telphone=input('get.telphone');
       $res=$this->checkUserExsits($telphone);
       if(!$res){
           ajaxReturn2(0,'用户账号不存在',url('User/regis'));
       }
    }
    
    public function checkUserExsits($telphone){
        return self::$cModel->checkUserExits($telphone);
    }
    //忘记密码
    public function Repsd(){
       $post_data=empty(input('get.'))?ajaxReturn2(0,'data is empty',''):input('get.');
       $Cvalidate=Loader::validate('Cvalidate');
       if(!$Cvalidate->check($post_data)){
           ajaxReturn2(-1,urlencode($Cvalidate->getError()));
       }
       $telphone=input('get.telphone');//忘记密码前提是有这个账号
       $s=checkPhone2($telphone);
       if(!$s){
           ajaxReturn2(-1,'telphone is error',$telphone);
       }
       $code=input('get.code');
       
       $res=$this->checkUserExsits($telphone);
       if(!$res){
           ajaxReturn2(404,'useraccount is not exsits',$telphone);
       }
       
       $check=$this->checkTextValidateCode($telphone,$code);
       if(!$check){
           ajaxReturn2(400,'validate is error',$check);
       }
       
       $password=empty(input('get.newpwd'))?ajaxReturn2(-1,'newpassword is require',''):input('get.newpwd');
       $newpasswd=md5($password);
       $re=self::$cModel->Repswd3($telphone, $newpasswd);
       if($re){
           ajaxReturn2(1,'password edit is true',url('User/login'));
       }else{
           ajaxReturn2(0,'password edit failed',$post_data);
       }
    }
    public function login($c="userinfo",$a="selectUserInfo"){
        $data=array('c'=>$c,'a'=>$a);
       
        return view('user2/login',array('d'=>$data));
    }
   //
   public function testRepwd(){
       $telphone='18795805742';
       $newpassword=md5('sjlovejj1314'.time());
      $re=self::$cModel->Repswd3($telphone, $newpassword);
      if($re){
          echo '密码修改成功,请重新登录';
          //修改成功JS跳转 或者程序控制跳转
      }else{
          echo '密码修改失败';
      }
   }
  //这里的是商家端的
   public function Home(){
       echo("我的主页");
       
   }
   public function index(){
      return view('index');
     // dump(cookie('pwd'));
      //dump(cookie('tel'));
       self::$cModel->RemoveCookie();
      // cookie(array('user_id','tel','password'))
   }
  public function register(){
      return view('user2/register');
  }
  public function regis(){
      return view('user2/register');
  }
  public function textlogins(){
      return view('user2/phoneLog');
  }
  public function forgetPwd(){
      return view('user2/forgetPwd');
  }
  public function modifyPwd(){
      return view('user2/modifyPwd');
  }
  
  /**
   * 
   * @return \think\response\View
   * 处理忘记密码简单的处理
   */
  public function process_password(){
      $post_data=empty(input('post.'))?ajaxReturn2(0,'data is empty',''):input('post.');
      $Cvalidate=Loader::validate('Cvalidate');
      if(!$Cvalidate->check($post_data)){
          ajaxReturn2(-1,urlencode($Cvalidate->getError()));
      }
      $telphone=input('post.telphone');//忘记密码前提是有这个账号
      $s=checkPhone2($telphone);
      if(empty($s)){
          ajaxReturn2(-1,'手机格式不正确',$telphone);
      }
      $code=input('post.code');
       
      $res=$this->checkUserExsits($telphone);
      if(!$res){
          ajaxReturn2(404,'useraccount is not exsits',$telphone);
      }
       
      $check=$this->checkTextValidateCode($telphone,$code);
      if(!$check){
          ajaxReturn2(400,'验证码错误',$check);
      }else{
          ajaxReturn2(200,'填写正确',url('newPwd'));
      }
      ajaxReturn2(200,'填写正确',url('newPwd'));
  }
  public function newPwd(){
      if(Request::instance()->isGet()){
          $telphone=input('get.telphone');
          return view('user2/newPwd',array('data'=>$telphone));//同过验证码修改密码
      }else{
          
      }
      
      //上面通过旧密码修改密码
  }
   public function loginOut(){
       session('user_id',null);
       session_destroy();
       $this->redirect('login');
   }
   public function RemoveCookie(){
       self::$cModel->RemoveCookie();
   }
   public function shangjiaLogin(){
       return view('user2/sellerLogin');
   }
   //重新设置密码
   public function Npwd(){
       $post_data=input('post.');
   }
   public function checkpasswd(){
       $telphone=input('get.telphone');
       $password=input('get.password');
       $res= self::$cModel->selectOldPasswod($telphone, $password);
      if($res){
          ajaxReturn2(0,'密码相同,重新设置密码',$telphone);
      }
   }
   public function checknewpass(){
       $password1=input('get.pwd');
       $password2=input('get.pwd2');
       if($password1!=$password2){
           ajaxReturn2(0,'俩次输入的密码不相同','');
       }
   }
   public function updatePwd(){
       $telphone=input('post.telphone');
       $password=input('post.password');
       $new2password=input('post.pwd2');
       $post_data=input('post.');
       $Validate=Loader::validate('Account');
       if(!$Validate->check($post_data)){
           ajaxReturn2(-1,$Validate->getError(),'');
       }
       
       $res=self::$cModel->selectOldPasswod($telphone, $password);
       if($res){
           ajaxReturn2(1,'密码最近相同','');
       }
       
       if($password!=$new2password){
           ajaxReturn2(2,'俩次输入密码不相同','');
       }
      $r=self::$cModel->Repswd3($telphone, $password);
      if($r){
          ajaxReturn2(3,'修改密码成功',url('api/user/login'));
      }else{
          ajaxReturn2(404,'密码修改失败','');
      }
       
   }
   public function login2(){
       return view();
   }
}